/* Check JER_Erasures_To_Erased(). */
#include <stdio.h>
#include <string.h>
#include "jerasure.h"
#include "reed_sol.h"

int main( int argc, char** argv )
{
	int *old_matrix;
	int *inverse_matrix;
	int i, j;
	int m = atoi( argv[1] );
	int k = atoi( argv[2] );
	int w = 8 << ( atoi( argv[3] ) % 3 );
	int size;
	unsigned char* buffer;
	char** data_ptrs;
	char** coding_ptrs;
	int *erasures;
	int *erased;
	int tmp;

	erasures = (int*) malloc( sizeof(int) );
	erasures[0] = -1;

	size = 8;
	
	srand48(m);
	buffer = (unsigned char*) malloc( sizeof(unsigned char) * (k+m) * size );
	data_ptrs = (char**) malloc( sizeof( char* ) * k );
	coding_ptrs = (char**) malloc( sizeof( char* ) * m );
	for( i = 0; i < k * size; i++ )
	{
		buffer[i] = lrand48() % 256;
		if( i % size == 0 )
			fprintf( stdout, "\n" );
		fprintf( stdout, "%x ", buffer[i] );
	}
	fprintf( stdout, "\n" );
	for( i = 0; i < k; i++ )
		data_ptrs[i] = buffer + i*size;
	for( i = 0; i < m; i++ )
		coding_ptrs[i] = buffer + k * size + i * size;
	old_matrix = reed_sol_vandermonde_coding_matrix( k, m, w );
	jerasure_matrix_encode( k, m, w, old_matrix, (char**)data_ptrs, 
			(char**)coding_ptrs, size );

	for( i = 0; i < (k+m) * size; i++ )
	{
		if( i % size == 0 )
			fprintf( stdout, "\n" );
		fprintf( stdout, "%x ", buffer[i] );
	}
	fprintf( stdout, "\n" );
	for( i = 0; i < m; i++ )
	{
		tmp = lrand48() % (k+m);
		for( j = 0; erasures[j] != -1 && erasures[j] != tmp; j++ );
		if( erasures[j] == -1 )
		{
			erasures = (int*) realloc( erasures, (j+2) * sizeof(int) );
			erasures[j] = tmp;
			erasures[j+1] = -1;
			if( tmp < k )
				memset( data_ptrs[tmp], 0, size );
			else
				memset( coding_ptrs[tmp-k], 0, size );
		}
	}
	for( i = 0; i < (k+m) * size; i++ )
	{
		if( i % size == 0 )
			fprintf( stdout, "\n" );
		fprintf( stdout, "%x ", buffer[i] );
	}
	fprintf( stdout, "\n" );

	jerasure_matrix_decode( k, m, w, old_matrix, 0, erasures, data_ptrs,
							coding_ptrs, size );

	for( i = 0; i < (k+m) * size; i++ )
	{
		if( i % size == 0 )
			fprintf( stdout, "\n" );
		fprintf( stdout, "%x ", buffer[i] );
	}
	fprintf( stdout, "\n" );
	return 0;
}
